<template>
    <div>
        <!-- <header>
            <router-link to="/drawMoney">
                提现 >
            </router-link>
        </header> -->
        <div class="title">
            <span>请上传身份证信息</span>
            <span>（身份证信息只能上传一次，请谨慎上传）</span>
        </div>
        <div class="cont">
            <div> <label for="upload_positive">
                    <img :src="!imagesPositive? require('../../asset/icon/icon_user_positive.png') : imagesPositive">
                    <input
                        @change="fileChange($event,'positive')"
                        type="file"
                        id="upload_positive"
                        style="display:none"
                        multiple
                    />
                </label>
                <p>请提交身份证正面照片</p>
            </div>
            <div>
                <label for="upload_negative">
                    <img :src="!imagesNegative? require('../../asset/icon/icon_user_negative.png') : imagesNegative">
                    <input
                        @change="fileChange($event,'negative')"
                        type="file"
                        id="upload_negative"
                        style="display:none"
                        multiple
                    />
                </label>
                <p>请提交身份证反面照片</p>
            </div>
        </div>
        <div
            class="button"
            @click="pushData"
        >
            上传实名信息
        </div>
    </div>
</template>
<script>
export default {
    name: "authentication",
    data() {
        return {
            imagesPositive: '',
            imagesNegative: '',
            selectType: '',
            QINIUtoken: '',
        };
    },
    methods: {
        getQiniuToken: function () {
            let params = {
                ossType: 'qiniu'
            };
            this.$post("/index/get_upload_token", params)
                .then((res) => {
                    if (res.code === 20000) {
                        this.QINIUtoken = res.data.upload_token
                    }
                }).catch((res) => {
                })
        },
        pushData() {
            if (!this.imagesPositive || !this.imagesNegative) {
                this.$dialog.toast({
                    mes: '请完善图片',
                    timeout: 1000,
                });
                return;
            }
            let params = {
                member_id: localStorage.getItem('token'),
                type: 'card',
                member_id_card_front: this.imagesNegative,
                member_id_card_back: this.imagesPositive,
            };

            this.$post("/wz_api/member/save", params)
                .then(res => {
                    if (res.code === 20000) {
                        this.$dialog.toast({
                            mes: '保存成功',
                            timeout: 1000,
                            callback: () => {
                                this.$router.back(-1)
                            }
                        });
                    }
                })
                .catch(err => { });

        },
        fileChange(el, type) {
            this.selectType = type
            if (!el.target.files[0].size) return;//判断是否有文件数量
            this.fileList(el.target.files);//获取files文件组传入处理
            el.target.value = ''//清空val值，以便可以重复添加一张图片
        },
        fileList(files) {
            for (let i = 0; i < files.length; i++) {
                this.fileAdd(files[i]);
            }
        },
        fileAdd(file) {
            let _this = this
            this.size = this.size + file.size;//总大小
            let reader = new FileReader();
            reader.vue = this;
            reader.readAsDataURL(file);
            reader.onload = function () {
                file.src = this.result;
                _this.pushBase(file.src)
            }
        },
        bytesToSize(bytes) {
            if (bytes === 0) return '0 B';
            let k = 1000, // or 1024
                sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                i = Math.floor(Math.log(bytes) / Math.log(k));
            return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
        },
        pushBase(code) {

            if (!this.QINIUtoken) {
                this.$dialog.toast('七牛云token错误，请联系客服！')
                return code
            }
            let _this = this
            _this.$indicator.open({
                text: '正在上传图片...',
                spinnerType: 'fading-circle'
            });
            let pic = code
            let timestamp = new Date().getTime()
            let key = window.btoa(timestamp + '.png')
            pic = pic.replace(/^data:image\/(jpeg|png|gif);base64,/, '')
            let url = 'http://upload.qiniup.com/putb64/-1/key/' + key // 非华东空间需要根据注意事项 1 修改上传域名
            let xhr = new XMLHttpRequest()
            xhr.open('POST', url, true)
            xhr.setRequestHeader('Content-Type', 'application/octet-stream')
            xhr.setRequestHeader('Authorization', 'UpToken ' + this.QINIUtoken)
            xhr.send(pic)
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    let data = JSON.parse(xhr.responseText)
                    if (_this.selectType == 'positive') {
                        _this.imagesPositive = _this.global.QINIU_URL + data.key

                    }
                    if (_this.selectType == 'negative') {
                        _this.imagesNegative = _this.global.QINIU_URL + data.key
                    }
                    _this.$indicator.close();
                    _this.$toast({
                        message: '上传成功',
                        position: 'middle',
                        duration: 1000,
                    });
                } else {
                    _this.imgUrl = code;
                }
            }
        },
        // 方法
    },
    beforeCreate() {
        document.querySelector("body").setAttribute("style", "background-color:#e1deff");
    },
    created() {
        // 实例创建完成
        this.getQiniuToken()
    },
};
</script>
<style lang="less" scoped>
@import url("../../asset/css/authentication");
</style>